package com.erp.app.util.web;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;

import com.erp.app.admin.errorMsg.criteria.ErrorMsgLabelSrchCriteria;
import com.erp.app.admin.errorMsg.vo.ErrorMsgLabelVo;
import com.erp.app.admin.projParam.vo.ProjectParamsList;
import com.erp.app.admin.sysParam.beans.SysParamList;
import com.erp.app.common.ProjectConstants;
import com.erp.app.common.select.beans.SelectDelegate;
import com.erp.app.common.util.ProjectCommonUtil;
import com.erp.common.web.GenericDocumentLinkRow;
import com.erp.common.web.LabelValueObj;
import com.erp.framework.SimpleConstants;
import com.erp.framework.controller.form.MultiRow;
import com.erp.framework.controller.form.SimpleBaseForm;
import com.erp.framework.controller.form.SimpleCoreForm;
import com.erp.framework.controller.form.SimpleMaintStyleForm;
import com.erp.framework.model.delegate.SimpleBaseDelegate;
import com.erp.framework.model.pk.SimpleBasePk;
import com.erp.framework.model.schema.MetaData;
import com.erp.framework.model.schema.TableSchema;
import com.erp.framework.util.BeanUtil;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.mainmenu.MenuObject;
import com.erp.framework.util.user.User;

public class WebUtil extends ProjectCommonUtil implements Serializable {
    public WebUtil() {
    }

    public static HashMap getModuleErrorMessages(String companyCode, String groupId, String menuId,
    		String langCode, String objectType){
		SimpleBaseDelegate spedg = new SimpleBaseDelegate();
	    ErrorMsgLabelVo errmsgVo = new ErrorMsgLabelVo();
	    ErrorMsgLabelSrchCriteria errmsgCrit = new ErrorMsgLabelSrchCriteria();
	    HashMap errmsgHash = new HashMap();

	    try{
		    errmsgCrit.setSrchCompanyCode(companyCode);
		    errmsgCrit.setSrchGroupIdFr(groupId);
		    errmsgCrit.setSrchGroupIdTo(groupId);
		    errmsgCrit.setSrchMenuIdFr(menuId);
		    errmsgCrit.setSrchMenuIdTo(menuId);
		    errmsgCrit.setSrchLangCodeFr(langCode);
		    errmsgCrit.setSrchLangCodeTo(langCode);
		    errmsgCrit.setSrchObjectTypeFr(objectType);
		    errmsgCrit.setSrchObjectTypeTo(objectType);

		    errmsgHash = spedg.selectByCriteria(errmsgVo, errmsgCrit);
	    }catch(Exception e){
	    	Logger.logExceptions(e);
	    }

	    return errmsgHash;
	}

    public static String getUserName(HttpSession session) {

        User user = (User) session.getAttribute(ProjectConstants.SESSION_USER);

        /*
         * ArrayList userDataAccessInfo =
         * (ArrayList)session.getAttribute(ProjectConstants.SESSION_USER_DATA_ACCESS_SECURITY);
         *
         * String userName = ""; if(userDataAccessInfo != null) { userName =
         * (String)((Hashtable)userDataAccessInfo.get(0)).get("USER_NAME"); }
         * else { userName = userid; }
         */
        String userName = user.getUserName();
        return userName;
    }

    public static boolean isAbleTo(String event, SimpleCoreForm form) {
        if (CommonUtil.isEmpty(event) || form == null)
            return false;

        Collection objs = form.getMenuObjectList();

        if (objs == null)
            return false;

        for (Iterator it = objs.iterator(); it.hasNext();) {
            MenuObject obj = (MenuObject) it.next();

            String action = CommonUtil.nullToString(obj.getObjectAction()).trim().toUpperCase();

            if (action.equals(event.trim().toUpperCase())) {
                if (ProjectConstants.GENERIC_YES.equals(obj.getEnableDisplay()) && ProjectConstants.GENERIC_YES.equals(obj.getVisibleDisplay()))
                    return true;
            }
        }

        return false;
    }

    public static String getUserDept(HttpSession session) {

        User user = (User) session.getAttribute(ProjectConstants.SESSION_USER);
        String dept = user.getDeptDesc();

        return dept;
    }

    public static String getUserGroupCode(HttpSession session) {

        User user = (User) session.getAttribute(ProjectConstants.SESSION_USER);
        String userGroupCode = user.getUserGroupCode();

        return userGroupCode;
    }

    public static ArrayList getUserApprovalList(HttpSession session) {

        User user = (User) session.getAttribute(ProjectConstants.SESSION_USER);
        String companyCode = user.getCompanyCode();
        String userGroupCode = WebUtil.getUserGroupCode(session);
        ArrayList resultList = new ArrayList();
        SelectDelegate sdg = new SelectDelegate();

        String table = "T_APPROVAL_LIST";
        String[] columns = { "USER_GROUP_CODE", "TASK_DOC", "STATUS", "IS_ACTIVE" };
        String where = "COMPANY_CODE='" + companyCode.toUpperCase() + "'" + " AND USER_GROUP_CODE='"
                + userGroupCode.toUpperCase() + "'";
        resultList = sdg.findFieldList(table, columns, where);

        return resultList;
    }

    public static boolean isRelDocRowViewable(GenericDocumentLinkRow docRow, User editingUser) {
    	SelectDelegate sdg = new SelectDelegate();
		String query = "";

		return true;
    }

    public static String getAppropriateCompanyCode(HttpSession session) {
        return getAppropriateCompanyCode(session, null);
    }

    public static String getAppropriateCompanyCode(HttpSession session, String paramId) {
        String companyCode = "";

        if (session == null)
            return companyCode;

        companyCode = (String) session.getAttribute(ProjectConstants.SESSION_COMPANY_CODE);
        // now always get the login company code as the appropriate company code
        /*
        if (paramId == null)
            return companyCode;

        SysParamList sysParam = (SysParamList) session.getAttribute(ProjectConstants.SESSION_SYS_PARAM);

        if (sysParam == null)
            return companyCode;

        ArrayList paramList = sysParam.getSysParamList();
        if (paramList == null)
            return companyCode;

        for (int i = 0; i < paramList.size(); i++) {
            SysParamVO vo = (SysParamVO) paramList.get(i);
            if (paramId.equals(vo.getParamId())) {
                if (ProjectConstants.GENERIC_YES.equals(vo.getParamVal())) {
                    // share the master
                    // so return general company code
                    companyCode = sysParam.getParamValById(ProjectConstants.SP_GENERAL_COMPANY_CODE);
                }

                break;
            }
        }
        */
        companyCode = (companyCode == null) ? "" : companyCode;

        return companyCode;
    }

    public static String getSysParamVal(HttpSession session, String paramId) {
        String paramVal = "";

        if (session == null)
            return paramVal;
        if (paramId == null)
            return paramVal;

        SysParamList sysParam = (SysParamList) session.getAttribute(ProjectConstants.SESSION_SYS_PARAM);

        if (sysParam == null)
            return paramVal;

        ArrayList paramList = sysParam.getSysParamList();
        if (paramList == null)
            return paramVal;

        paramVal = sysParam.getParamValById(paramId);
        paramVal = (paramVal == null) ? "" : paramVal;

        return paramVal;
    }

    public static String getPrjParamVal(HttpSession session, String paramId) {
        String paramVal = "";

        if (session == null)
            return paramVal;
        if (paramId == null)
            return paramVal;

        ProjectParamsList projectParam = (ProjectParamsList) session.getAttribute(ProjectConstants.SESSION_PROJECT_PARAM);

        if (projectParam == null)
            return paramVal;

        ArrayList paramList = projectParam.getProjectParamsList();
        if (paramList == null)
            return paramVal;

        paramVal = projectParam.getPrjParamValById(paramId);
        paramVal = (paramVal == null) ? "" : paramVal;

        return paramVal;
    }

    public static String getLabel(ArrayList statusList, String value) {
        String label = "";

        if (statusList == null || statusList.size() <= 0)
            return label;

        for (int i = 0; i < statusList.size(); i++) {
            LabelValueObj lvObj = (LabelValueObj) statusList.get(i);

            if (value != null) {
                if (value.equals(lvObj.getValue())) {
                    label = lvObj.getLabel();
                    break;
                }
            } else {
                if (lvObj.getValue() == null) {
                    label = lvObj.getLabel();
                    break;
                }
            }
        }

        return label;
    }

    public static String getLabel(Collection list, String value) {
        String label = "";
        LabelValueObj lvo = null;

        if (list == null || value == null)
            return value != null ? value : label;

        Iterator it = list.iterator();

        while (it.hasNext()) {
            lvo = (LabelValueObj) it.next();

            if (lvo.getValue() == null)
                continue;

            if (lvo.getValue().equals(value)) {
                label = lvo.getLabel();
                break;
            }
        }

        return label == null ? "" : label;
    }

    public static String getCodeSysParamId(String masterRefCode) {
        String paramId = "";
        paramId = "SP_SHARE_" + CommonUtil.nullToString(masterRefCode).toUpperCase();

        return paramId;
    }

    public static String getStatusLabel(String status, ArrayList statusList) {

        String label = "";

        if (status == null || statusList == null)
            return label;

        for (int i = 0; statusList != null && i < statusList.size(); i++) {
            LabelValueObj lvObj = (LabelValueObj) statusList.get(i);

            if (lvObj.getValue() == null)
                continue;

            if (lvObj.getValue().equals(status)) {
                label = lvObj.getLabel();
                break;
            }
        }

        return label == null ? "" : label;
    }

	public static String openFlashDo() {
        return openPopWindow("openFlash.do", "openFlashDo", "530", "600", "no", "no", "no", "no", true);
    }
	public static String openSendEmailDo() {
        return openPopWindow("sendEmail.do", "openSendEmailDo", "600", "400", "yes", "no", "yes", "yes", true);
    }

    public static String openSearchDo() {
        return openPopWindow("search.do", "searchWin", "600", "450", "yes", "no", "yes", "yes", true);
    }

    public static String openRemarkTextDo() {
        return openPopWindow("remarkText.do", "remarkWin", "520", "250", "yes", "no", "yes", "yes", true);
    }

    public static String openSelectRemarkTextDo() {
        return openPopWindow("selectRemarkText.do", "selectRemarkWin", "520", "250", "yes", "no", "yes", "yes", true);
    }

    public static String openPopUpDo() {
        return openPopWindow("popUp.do", "popUpWin", "700", "400", "yes", "no", "yes", "yes", true);
    }

    public static String openEnquiryDo() {
        return openPopWindow("enquiry.do", "enquiryWin", "800", "600", "yes", "no", "yes", "yes", true);
    }
    
    public static String openEditBrandDept() {
        return openPopWindow("custDept.do?pageEvent=doNothing", "Department", "800", "600", "yes", "no", "yes", "yes", true);
    }

    
    public static String openCompanyMasterDo() {
        return openGenericDo("companyMasterMaintenance.do?pageEvent=viewCompLogo", "companyMasterWin");
    }

    public static String openCompanyMasterBannerLogoDo() {
        return openGenericDo("companyMasterMaintenance.do?pageEvent=viewBannerLogo", "companyMasterWin");
    }

    public static String openCompanyMasterBannerBGDo() {
        return openGenericDo("companyMasterMaintenance.do?pageEvent=viewBannerBG", "companyMasterWin");
    }

   /* public static String openOsTaskSummary() {
        return openPopWindow("osTaskSummary.do", "osTaskSummary", "800", "600", "yes", "no", "yes", "yes", true);

    }*/
    public static String openUploadFileDo() {
        return openPopWindow("uploadFile.do", "uploadWin", "600", "500", "yes", "no", "yes", "yes", true);
    }

    public static String openAlertTask() {
        return openPopWindow("projMaintenance.do", "projMaintenance", "930", "620", "yes", "no", "yes", "yes", true);
    }
    

    public static String openProjShowStyleDetailDo(String styleLineNo) {
    	return "win  = window.open('projShowStyleDetail.do?pageEvent=showStyleDetail&popupStyleLineNo="+styleLineNo+"','projShowStyleDetail',"
    	+"'top=0,left=0,width=930,height=620,resizable=yes," 
    	+ "menubar=no,scrollbars=yes,status=yes');"
    	+ " win.focus();";
//        return openPopWindow("projPopupStyleDetail.do?pageEvent=popupStyleDetail&popupStyleLineNo="+styleLineNo+"", "projPopupStyleDetail", "930", "620", "yes", "no", "yes", "yes", true);
    }
    
//    public static String openProjShowStyleFabricColorDo() {
//    	return "win  = window.open('projStyleFabricColor.do?pageEvent=search','projShowStyleFabricColor',"
//    	+"'top=0,left=0,width=930,height=620,resizable=yes," 
//    	+ "menubar=no,scrollbars=yes,status=yes');"
//    	+ " win.focus();";
////        return openPopWindow("projPopupStyleDetail.do?pageEvent=popupStyleDetail&popupStyleLineNo="+styleLineNo+"", "projPopupStyleDetail", "930", "620", "yes", "no", "yes", "yes", true);
//    }
    
    public static String openProjShowStyleFabricColorDo() {
    	return "win  = window.open('projShowStyleFabricColor.do?pageEvent=doNothing','projShowStyleFabricColor',"
    	+"'top=0,left=0,width=930,height=620,resizable=yes," 
    	+ "menubar=no,scrollbars=yes,status=yes');"
    	+ " win.focus();";
//        return openPopWindow("projPopupStyleDetail.do?pageEvent=popupStyleDetail&popupStyleLineNo="+styleLineNo+"", "projPopupStyleDetail", "930", "620", "yes", "no", "yes", "yes", true);
    }
    
    public static String openProjPopupStyleDetailDo(String styleLineNo) {
    	return "win  = window.open('projPopupStyleDetail.do?pageEvent=popupStyleDetail&popupStyleLineNo="+styleLineNo+"','projPopupStyleDetail',"
    	+"'top=0,left=0,width=930,height=620,resizable=yes," 
    	+ "menubar=no,scrollbars=yes,status=yes');"
    	+ " win.focus();";
//        return openPopWindow("projPopupStyleDetail.do?pageEvent=popupStyleDetail&popupStyleLineNo="+styleLineNo+"", "projPopupStyleDetail", "930", "620", "yes", "no", "yes", "yes", true);
    }
    
    public static String openFabricCommitWSAHistoryDo() {
    	 return "win  = window.open('fabricCommitWSAHistMaintenance.do?pageEvent=edit','fabricCommitWSAHistory',"
	     	+"'top=0,left=0,width=930,height=620,resizable=yes," 
	     	+ "menubar=no,scrollbars=yes,status=yes');"
	     	+ " win.focus();";
    }

    public static String openProjPopupCostDetailDo() {
    	
        return "win  = window.open('projCostingMaintenance.do?pageEvent=edit','projPopupCostDetail',"
        	+"'top=0,left=0,width=930,height=620,resizable=yes," 
        	+ "menubar=no,scrollbars=yes,status=yes');"
        	+ " win.focus();";
        
//        return openPopWindow("projCostingMaintenance.do?pageEvent=edit", "projPopupCostDetail", "930", "620", "yes", "no", "yes", "yes", true);
    }

    public static String openProjPopupCostDetailHistDo() {
        return openPopWindow("projCostingHistSearch.do", "projPopupCostDetailHist", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openProjPopupFabricTaskDetailDo(String pageEventSrc) {
        return openPopWindow("projPopupFabricTaskDetail.do?pageEvent=popupFabricTaskDetail&"+pageEventSrc+"", "projPopupFabricTaskDetail", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openProjViewStyleAttach(String pageEventSrc) {
        return openPopWindow("projMaintenance.do?pageEvent=showStyleAttach&pageEventSrc="+pageEventSrc+"", "projViewStyleAttach", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openProjViewStyleTaskAttach(String pageEventSrc) {
        return openPopWindow("projStyleTaskMaintenance.do?pageEvent=showTaskAttach&pageEventSrc="+pageEventSrc+"", "projViewStyleAttach", "800", "600", "yes", "no", "yes", "yes", true);
    }
    
    public static String openProjViewStyleTaskMultiAttach(String pageEventSrc) {
        return openPopWindow("projStyleTaskMulti.do?pageEvent=showTaskAttach&pageEventSrc="+pageEventSrc+"", "projViewStyleAttach", "800", "600", "yes", "no", "yes", "yes", true);
    }
    
    public static String openPopupStyleTaskDo(String pageEventSrc) {
    	
    	return "win  = window.open('projStyleTaskSearch.do?pageEvent=edit"+pageEventSrc+"','popupStyleTaskDetail',"
    	+"'top=0,left=0,width=930,height=620,resizable=yes," 
    	+ "menubar=no,scrollbars=yes,status=yes');"
    	+ " win.focus();";
    	
//        return openPopWindow("projStyleTaskSearch.do?pageEvent=edit"+pageEventSrc+"", "popupStyleTaskDetail", "930", "620", "yes", "no", "yes", "yes", true);
    }
    
    public static String openPopupMultiStyleTaskDo(String pageEventSrc) {
    	
        return openPopWindow("projStyleTaskSearch.do?pageEvent=editMulti"+pageEventSrc+"", "popupMutilStyleTask", "930", "620", "yes", "no", "yes", "yes", true);
    }

    public static String openPopupFabricTaskDo(String pageEventSrc) {
    	return "win  = window.open('projFabricTaskSearch.do?pageEvent=edit"+pageEventSrc+"','popupFabricTaskDetail',"
    	+"'top=0,left=0,width=930,height=620,resizable=yes," 
    	+ "menubar=no,scrollbars=yes,status=yes');"
    	+ " win.focus();";
    	
//        return openPopWindow("projFabricTaskSearch.do?pageEvent=edit"+pageEventSrc+"", "popupFabricTaskDetail", "930", "620", "yes", "no", "yes", "yes", true);
    }
    
    public static String openProjShowDeliveryColorDo() {
        return openPopWindow("projShowDeliveryColor.do?pageEvent=doNothing", "projShowDeliveryColor", "1000", "620", "yes", "no", "yes", "yes", true);
    }
    
    public static String openProjShowFabricDateDo() {
        return openPopWindow("projShowFabricDate.do?pageEvent=doNothing", "projShowFabricDate", "800", "600", "yes", "no", "yes", "yes", true);
    }
    public static String openProjShowFabricDetailDateDo() {
        return openPopWindow("projShowFabricDetailDate.do?pageEvent=doNothing", "projShowFabricDetailDate", "800", "600", "yes", "no", "yes", "yes", true);
    }
    public static String openProjEditFabricDetailDo() {
        return openPopWindow("projEditFabricDetail.do?pageEvent=doNothing", "projEditFabricDetail", "800", "600", "yes", "no", "yes", "yes", true);
    }
    
    public static String openSyncOtherProjFabricTask() {
        return openPopWindow("syncFabricTask.do", "SyncProjectFabricTaskData", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openSyncRelatedProjStyle(String projNo) {
        return openPopWindow("relatedProjStyleMaintenance.do?pageEvent=edit&projNo="+projNo, "SyncProjectFabricTaskData", "800", "600", "yes", "no", "yes", "yes", true);
    }
    
    public static String openProjShowStyleFabricDo() {
        return openPopWindow("projShowStyleFabric.do?pageEvent=doNothing", "projShowStyleFabric", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openProjShowDeliveryQtyDo() {
        return openPopWindow("projShowDeliveryQty.do?pageEvent=doNothing", "projShowDeliveryColor", "800", "600", "yes", "no", "yes", "yes", true);
    }
    
    public static String openProjDeliveryShowDeliveryColorDo() {
        return openPopWindow("projDeliveryColor.do?pageEvent=popupDeliveryColor", "projShowDeliveryColor", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openFabricTaskViewDtlDo() {
        return openPopWindow("fabTaskViewDtl.do?pageEvent=doNothing", "popupTaskViewDtl", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openFabricTaskSetSeqDo() {
        return openPopWindow("fabTaskSetSeq.do?pageEvent=doNothing", "fabricTaskSetSeq", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openStyleTaskShowDtlInfoDo() {
        return openPopWindow("styleTaskShowDtlInfo.do?pageEvent=doNothing", "popupTaskViewDtl", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openStyleTaskSetSeqDo() {
        return openPopWindow("styleTaskSetSeq.do?pageEvent=doNothing", "styleTaskSetSeq", "800", "600", "yes", "no", "yes", "yes", true);
    }

    public static String openFcLaterViewStyleDo() {
        return openPopWindow("fcLaterPopupViewStyle.do?pageEvent=doNothing", "popupViewStyle", "800", "600", "yes", "no", "yes", "yes", true);
    }


    public static String openGenericDo(String dotDo, String winName) {
        return openPopWindow(dotDo, winName, "600", "450", "yes", "no", "yes", "yes", true);
    }

    
    public static String openPopWindow(String dotDo, String winName, String width, String height, String resizable,
            String menubar, String scrollbars, String status, boolean focus) {
        // window.resizeTo(800, 800);
        // window.moveTo(0, 0);

        String str = "";
        str = "win  = window.open('" + dotDo + "','" + winName + "','width=" + width + ",height=" + height + ",resizable="
                + resizable + "," + "menubar=" + menubar + ",scrollbars=" + scrollbars + ",status=" + status + "');";

        if (focus) {
            str += " win.focus();";
        }

        return str;
    }

    public static String getDataAccessSecurityWhereClause(HttpSession session, String deptFieldName, String userFieldName) {
        ArrayList userDataAccessInfo = (ArrayList) session.getAttribute(ProjectConstants.SESSION_USER_DATA_ACCESS_SECURITY);
        // String orderDept = "";
        // ArrayList resultList = new ArrayList();

        String allWhere = "";
        String ownerWhere = "";
        String otherWhere = "";

        if ((userDataAccessInfo != null) && (!userDataAccessInfo.isEmpty())) {
            for (int i = 0; i < userDataAccessInfo.size(); i++) {
                Hashtable hash = (Hashtable) userDataAccessInfo.get(i);
                String accessStatus = (String) hash.get("ACCESS_STATUS");
                String accessUserCode = (String) hash.get("ACCESS_USER_CODE");
                String accessDept = (String) hash.get("ACCESS_DEPT");
                String userCode = (String) hash.get("USER_CODE");
                if ((ProjectConstants.GENERIC_YES.equals(accessStatus)) && (ProjectConstants.ACCESS_ALL.equals(accessUserCode))) {
                    if ("".equals(allWhere)) {
                        allWhere = "(" + deptFieldName + "='" + accessDept + "')";
                    } else {
                        allWhere += " OR (" + deptFieldName + "='" + accessDept + "')";
                    }
                } else if ((ProjectConstants.GENERIC_YES.equals(accessStatus)) && (ProjectConstants.ACCESS_OWNER.equals(accessUserCode))) {
                    if ("".equals(ownerWhere)) {
                        ownerWhere = userFieldName + "='" + userCode + "' and " + deptFieldName + "='" + accessDept + "'";
                    }
                } else if (ProjectConstants.GENERIC_YES.equals(accessStatus)) {
                    if ("".equals(otherWhere)) {
                        otherWhere = "(" + userFieldName + "='" + accessUserCode + "' AND " + deptFieldName + "='" + accessDept
                                + "')";
                    } else {
                        otherWhere += " OR (" + userFieldName + "='" + accessUserCode + "' AND " + deptFieldName + "='"
                                + accessDept + "')";
                    }

                }
            }
        } else {
            System.out.println("WebUtil.getDataAccessSecurityWhereClause(): " + "the User Data Access Info ArrayList is empty.");
        }

        String tmpWhere = "";
        if (!"".equals(allWhere)) {
            tmpWhere = allWhere;
        }

        if (!"".equals(ownerWhere)) {
            if ("".equals(tmpWhere)) {
                tmpWhere = ownerWhere;
            } else {
                tmpWhere = tmpWhere + " OR (" + ownerWhere + ")";
            }
        }

        if (!"".equals(otherWhere)) {
            if ("".equals(tmpWhere)) {
                tmpWhere = otherWhere;
            } else {
                tmpWhere = tmpWhere + " OR (" + otherWhere + ")";
            }
        }

        return tmpWhere;
    }

    public static String getDataAccessSecurityWhereClause(HttpSession session, String deptFieldName) {
        ArrayList userDataAccessInfo = (ArrayList) session.getAttribute(ProjectConstants.SESSION_USER_DATA_ACCESS_SECURITY);
        // String orderDept = "";
        // ArrayList resultList = new ArrayList();

        // where = "ORDER_DEPT in ('112233', '333', '1122')
        String allWhere = "";
        String ownerWhere = "";
        String otherWhere = "";

        if ((userDataAccessInfo != null) && (!userDataAccessInfo.isEmpty())) {
            for (int i = 0; i < userDataAccessInfo.size(); i++) {
                java.util.Hashtable hash = (java.util.Hashtable) userDataAccessInfo.get(i);
                String accessStatus = (String) hash.get("ACCESS_STATUS");
                String accessUserCode = (String) hash.get("ACCESS_USER_CODE");
                String accessDept = (String) hash.get("ACCESS_DEPT");
                String userCode = (String) hash.get("USER_CODE");
                if ((ProjectConstants.GENERIC_YES.equals(accessStatus)) && (ProjectConstants.ACCESS_ALL.equals(accessUserCode))) {
                    if ("".equals(allWhere)) {
                        allWhere = "(" + deptFieldName + "='" + accessDept + "')";
                    } else {
                        allWhere += " OR (" + deptFieldName + "='" + accessDept + "')";
                    }
                } else if ((ProjectConstants.GENERIC_YES.equals(accessStatus)) && (ProjectConstants.ACCESS_OWNER.equals(accessUserCode))) {
                    if ("".equals(ownerWhere)) {
                        ownerWhere = deptFieldName + "='" + accessDept + "'";
                    }
                } else if (ProjectConstants.GENERIC_YES.equals(accessStatus)) {
                    if ("".equals(otherWhere)) {
                        otherWhere = "(" + deptFieldName + "='" + accessDept + "')";
                    } else {
                        otherWhere += " OR (" + deptFieldName + "='" + accessDept + "')";
                    }

                }
            }
        } else {
            System.out.println("WebUtil.getDataAccessSecurityWhereClause(): " + "the User Data Access Info ArrayList is empty.");
        }

        String tmpWhere = "";
        if (!"".equals(allWhere)) {
            tmpWhere = allWhere;
        }

        if (!"".equals(ownerWhere)) {
            if ("".equals(tmpWhere)) {
                tmpWhere = ownerWhere;
            } else {
                tmpWhere = tmpWhere + " OR (" + ownerWhere + ")";
            }
        }

        if (!"".equals(otherWhere)) {
            if ("".equals(tmpWhere)) {
                tmpWhere = otherWhere;
            } else {
                tmpWhere = tmpWhere + " OR (" + otherWhere + ")";
            }
        }

        return tmpWhere;
    }

    public static String getImagePath(ServletContext sc) {
        return sc.getRealPath((String) sc.getInitParameter(ProjectConstants.SERVLET_CONTEXT_KEY_IMAGE_PATH)) + File.separator;
    }

    public static boolean isValidationSkippable(MultiRow row) {
        return !ProjectCommonUtil.isEmpty(row.getIsDelete());
    }

    public static boolean validateCode(String code, String label, ActionErrors errors) {
        return validateCode(code, label, errors, false);
    }

    public static boolean validateCode(String code, String label, ActionErrors errors, boolean spaceAllowed) {
        char[] invalidCharacters = (spaceAllowed) ? ActionErrorUtil.INVALID_CODE_CHARACTERS_WITHOUT_SPACE : ActionErrorUtil.INVALID_CODE_CHARACTERS;
        boolean validCode = WebUtil.isValidCode(code, invalidCharacters);
        if (!validCode) {
            ActionErrorUtil.addErrorForInvlalidCode(errors, label, invalidCharacters);
        }
        return validCode;
    }

    public static boolean validateNonBlankField(String value, String label, ActionErrors errors) {
        boolean blank = isEmpty(value);
        if (blank) {
            ActionErrorUtil.addErrorForGeneralFieldBlank(errors, label);
        }
        return !blank;
    }

    public static boolean validateDate(
            String date, String label, boolean required, ActionErrors errors) {
    	return validateDate(date, SimpleConstants.INPUT_DATE_FORMAT, label, required, errors);
    }

    public static boolean validateDate(
        String date, String label, MetaData metadata, ActionErrors errors) {
        boolean validDate = validateDate(date, SimpleConstants.INPUT_DATE_FORMAT, label, metadata.isNullable(), errors);
        if (validDate) {
            if (metadata.isNdcDate()) {
                Calendar c = Calendar.getInstance();
                c.setTime(CommonUtil.stringToDate(date));
                if (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
                    ActionErrorUtil.addErrorForInvalidNdcDate(errors, label);
                    return false;
                }
            }
        }
        return validDate;
    }

    public static boolean validateDate(
            String date, String dateFormat, String label, boolean required, ActionErrors errors) {
        if (isEmpty(date)) {
            if (required) {
                ActionErrorUtil.addErrorForGeneralFieldBlank(errors, label);
                return false;
            } else {
                return true;
            }
        }
        boolean validDate = CommonUtil.isValidDate(date, dateFormat);
        if (!validDate) {
            ActionErrorUtil.addErrorForInvalidDate(errors, label);
        }
        return validDate;
    }

    public static boolean validateYear(String year, String label, ActionErrors errors) {
        boolean validYear = !isEmpty(year) && isValidNumber(year, 4, 0);
        if (validYear && !"0".equals(year) && year.length() == 4) {
            int yearAsInt = Integer.parseInt(year);
            validYear = ProjectCommonUtil.isBetween(yearAsInt, 1970, 2100);
        }
        if (!validYear) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ActionErrorUtil.ERROR_INVALID_YEAR_FORMAT, label));
        }
        return validYear;
    }

    public static boolean validateMonth(String month, String label, ActionErrors errors) {
        boolean validMonth = !isEmpty(month) && isValidNumber(month, 2, 0);
        if (validMonth && !"0".equals(month)) {
            int monthAsInt = Integer.parseInt(month);
            validMonth = ProjectCommonUtil.isBetween(monthAsInt, 1, 12);
        }
        if (!validMonth) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ActionErrorUtil.ERROR_INVALID_MONTH_FORMAT, label));
        }
        return validMonth;
    }

    public static boolean validateValidNumber(String number, int length, int precision, String label, boolean required, ActionErrors errors) {
        boolean validNumber = (!required && isEmpty(number)) || isValidNumber(number);
        if (!validNumber) {
            ActionErrorUtil.addErrorForInvalidNumber(errors, label);
        }
        return validNumber;
    }

    public static boolean validatePositiveNumber(String number, int length, int precision, String label, boolean required, ActionErrors errors) {
        boolean validNumber = (!required && isEmpty(number)) || isValidNumber(number);
    	if (validNumber && !isEmpty(number)){
    		validNumber = CommonUtil.isValidPositiveNumber(number);
    		if (!validNumber) {
    			ActionErrorUtil.addErrorForInvalidPositiveNumber(errors, label);
    		}
    	}
    	return validNumber;
    }

    public static boolean validateNegativeNumber(String number, int length, int precision, String label, boolean required, ActionErrors errors) {
        boolean validNumber = (!required && isEmpty(number)) || isValidNumber(number);
        if (validNumber && !isEmpty(number)){
            validNumber = CommonUtil.isValidNegativeNumber(number);
            if (!validNumber) {
                ActionErrorUtil.addErrorForInvalidNegativeNumber(errors, label);
            }
        }
        return validNumber;
    }

    public static boolean validateNonnegativeNumber(String number, int length, int precision, String label, boolean required, ActionErrors errors) {
        boolean validNumber = (!required && isEmpty(number)) || isValidNumber(number);
        if (validNumber && !isEmpty(number)){
            validNumber = CommonUtil.isValidPositiveNumberOrZero(number);
            if (!validNumber) {
                ActionErrorUtil.addErrorForInvalidNonNegativeNumber(errors, label);
            }
        }
        return validNumber;
    }

    public static boolean validateValidInteger(String number, String label, boolean required, ActionErrors errors) {
        boolean validNumber = (!required && isEmpty(number)) || isValidInteger(number);
        if (!validNumber) {
            ActionErrorUtil.addErrorForInvalidInteger(errors, label);
        }
        return validNumber;
    }

    public static boolean validatePrecisionScale(String number, int precision, int scale, String label, boolean required, ActionErrors errors) {
        boolean validPrecisionScale = (!required && isEmpty(number)) || isValidPrecisionScale(number, precision, scale);
        if (!validPrecisionScale) {
            ActionErrorUtil.addErrorForInvalidNumber(errors, label);
        }
        return validPrecisionScale;
    }

    public static boolean validatePositiveInteger(String number, String label, boolean required, ActionErrors errors) {
        boolean validNumber = (!required && isEmpty(number)) || isValidInteger(number);
        if (validNumber && !isEmpty(number)){
            validNumber = CommonUtil.isValidPositiveInteger(number);
            if (!validNumber) {
                ActionErrorUtil.addErrorForInvalidPositiveInteger(errors, label);
            }
        }
        return validNumber;
    }

    public static boolean validateNegativeInteger(String number, String label, boolean required, ActionErrors errors) {
        boolean validNumber = (!required && isEmpty(number)) || isValidInteger(number);
        if (validNumber && !isEmpty(number)){
            validNumber = CommonUtil.isValidNegativeInteger(number);
            if (!validNumber) {
                ActionErrorUtil.addErrorForInvalidNegativeInteger(errors, label);
            }
        }
        return validNumber;
    }

    public static boolean validateNonnegativeInteger(String number, String label, boolean required, ActionErrors errors) {
        boolean validNumber = (!required && isEmpty(number)) || isValidInteger(number);
        if (validNumber && !isEmpty(number)){
            validNumber = CommonUtil.isValidNegativeIntegerOrZero(number);
            if (!validNumber) {
                ActionErrorUtil.addErrorForInvalidNonNegativeInteger(errors, label);
            }
        }
        return validNumber;
    }

    public static boolean validateEmailAddress(String email, String label, boolean required, ActionErrors errors) {
        if (!required && isEmpty(email)) return true;
        boolean validEmailAddress = true;
        try {
            EmailValidator.isValidEmailAddr(label, email);
        } catch (Exception e) {
            validEmailAddress = false;
        }
        if (!validEmailAddress) {
            ActionErrorUtil.addErrorForInvlalidEmailAddress(errors, label);
        }
        return validEmailAddress;
    }

    public static boolean validatePhoneNumber(
            String countryCode, String areaCode, String phoneNumber,
            String countryCodeLabel, String areaCodeLabel, String phoneNumberLabel,
            boolean required, ActionErrors errors) {
        return !required || validateNonBlankField(getString(countryCode, "") + getString(areaCode, "") + getString(phoneNumber, ""), phoneNumberLabel, errors);
    }

    public static boolean isValidCode(String code) {
        return isValidCode(code, ActionErrorUtil.INVALID_CODE_CHARACTERS);
    }

    public static boolean isValidCode(String code, char[] invalidCharacters) {
        if (isEmpty(code)) return false;
        for (int i = 0; i < invalidCharacters.length; ++i) {
            if (code.indexOf(invalidCharacters[i]) != -1) {
                return false;
            }
        }
        return true;
    }

    public static String getChildLabel(String parent, int lineNo, String label) {
    	return parent + " " + label + ActionErrorUtil.ERROR_CHILD_IND + lineNo;
    }

    public static int getNonDeletedRowCount(ArrayList rows) {
    	int count = 0;
    	if (rows != null && rows.size() > 0) {
    		for (int i=0; i<rows.size(); i++) {
    			MultiRow row = (MultiRow) rows.get(i);
    			if (CommonUtil.isEmpty(row.getIsDelete())) {
    				count++;
    			}
    		}
    	}
    	return count;
    }

    public static int getCurrentIdx(SimpleCoreForm form) {
        return (form instanceof SimpleMaintStyleForm) ? ((SimpleMaintStyleForm) form).getCurrIdx() : 0;
    }

    public static MultiRow addRow(SimpleCoreForm form, Class[] childRowClass, int currentIdx) {
        try {
            MultiRow rowToAdd = (MultiRow) childRowClass[currentIdx].newInstance();
            int originalIdx = form.getCurrIdx();
            form.setCurrIdx(currentIdx);
            form.addRow(rowToAdd);
            form.setCurrIdx(originalIdx);
            return rowToAdd;
        } catch (InstantiationException e) {
            Logger.logExceptions(form, e);
            return null;
        } catch (IllegalAccessException e) {
            Logger.logExceptions(form, e);
            return null;
        }
    }

    public static MultiRow addRow(SimpleCoreForm form, Class[] childRowClass) {
        return addRow(form, childRowClass, getCurrentIdx(form));
    }

    public static MultiRow addRow(SimpleCoreForm form, Class[] childRowClass, SimpleBasePk pk) {
        MultiRow row = addRow(form, childRowClass, getCurrentIdx(form));
        try {
            Map pkMap = BeanUtils.describe(pk);
            pkMap.remove("class");
            BeanUtils.populate(row, pkMap);
        } catch (IllegalAccessException e) {
            Logger.logExceptions(row, e);
        } catch (InvocationTargetException e) {
            Logger.logExceptions(row, e);
        } catch (NoSuchMethodException e) {
            Logger.logExceptions(row, e);
        }
        return row;
    }

    public static MultiRow delRow(SimpleCoreForm form, int currentIdx, int pageEventSrc) {
        MultiRow rowToDel = getRow(form, currentIdx, pageEventSrc);
        if (rowToDel != null) rowToDel.setIsDelete("checked");
        return rowToDel;
    }

    public static MultiRow delRow(SimpleCoreForm form, int currentIdx) {
        return delRow(form, currentIdx, Integer.parseInt(form.getPageEventSrc()));
    }

    public static MultiRow getRow(SimpleCoreForm form, int currentIdx, int pageEventSrc) {
        return (MultiRow) form.getMultiRows(currentIdx).get(pageEventSrc);
    }

    public static MultiRow delCurrentRow(SimpleCoreForm form) {
        return delRow(form, getCurrentIdx(form), Integer.parseInt(form.getPageEventSrc()));
    }

    public static MultiRow getCurrentRow(SimpleCoreForm form) {
        return getCurrentRow(form, getCurrentIdx(form));
    }

    public static MultiRow getCurrentRow(SimpleCoreForm form, int currentIdx) {
        return getRow(form, currentIdx, Integer.parseInt(form.getPageEventSrc()));
    }

    public static TableSchema findTs(Object object, SimpleCoreForm form) {
        return findTs(object, form, "");
    }

    public static boolean isReadOnly(Object object, SimpleCoreForm form) {
        if (object == null) return false;
        if (object instanceof MultiRow) {
            return ((MultiRow) object).isReadOnly() || (form != null && form.isReadOnly());
        } else if (object instanceof SimpleCoreForm) {
            return ((SimpleCoreForm) object).isReadOnly();
        } else {
            return false;
        }
    }

    public static TableSchema findTs(Object object, SimpleCoreForm form, String childTsIndex) {
        TableSchema ts = null;
        if (object instanceof MultiRow) {
            if (SimpleConstants.FORM_TYPE_MAINT.equals(form.getFormType())) {
                ts = ((MultiRow) object).getTs();
            } else {
                Logger.log(object, "form's page mode: " + form.getPageMode());
                ts = form.getTs();
            }
        } else {
            if (object instanceof SimpleCoreForm) form = (SimpleCoreForm) object;
            ts = form.getTs();
            if (!CommonUtil.isEmpty(childTsIndex)) {
                int index = Integer.parseInt(childTsIndex);
                ts = (index >= 0 && index < form.getChildTs().length) ? form.getChildTs()[index] : null;
            }
        }
        return ts;
    }

    public static String formatOutput(Object object, MetaData metadata, Object value, int decimalPlaces) {
        if (value == null) return CommonUtil.nullToString(value);
        if (CommonUtil.isValidNumber(CommonUtil.getString(value)) && decimalPlaces >= 0) {
            value = CommonUtil.formatNumber(value.toString(), NumberFormats.getDecimalPlacesString(decimalPlaces, false));
        } else if (metadata != null) {
            try {
                Class propertyClass = Class.forName(metadata.getColumnClassName());
                if (Timestamp.class.isAssignableFrom(propertyClass)) {
                    value = CommonUtil.dateToString(CommonUtil.stringToTimestamp(value.toString()), SimpleConstants.OUTPUT_DATE_FORMAT);
                } else if (Date.class.isAssignableFrom(propertyClass)) {
                    value = (value instanceof Date) ? CommonUtil.dateToString((Date) value, SimpleConstants.OUTPUT_DATE_FORMAT) : value;
                }
            } catch (ClassNotFoundException e) {
                Logger.logExceptions(object, e);
            }
        }
        return CommonUtil.nullToString(value.toString());
    }

    public static boolean isModeCreate(Object formOrMultiRow) {
        return (formOrMultiRow instanceof SimpleBaseForm)
            ? SimpleConstants.PAGE_MODE_CREATE.equals(((SimpleBaseForm) formOrMultiRow).getPageMode())
            : (formOrMultiRow instanceof MultiRow)
            ? SimpleConstants.ROW_MODE_CREATE.equals(((MultiRow) formOrMultiRow).getRowMode())
            : false;
    }

    public static MultiRow copyCurrentRow(SimpleCoreForm form, Class[] childRowClass) {
        MultiRow newRow = WebUtil.addRow(form, childRowClass);
        String originalIdx = newRow.getIdx();
        String originalRowMode = newRow.getRowMode();
        BeanUtil.copyPropertiesDefault(newRow, WebUtil.getCurrentRow(form));
        newRow.setIdx(originalIdx);
        newRow.setRowMode(originalRowMode);
        BeanUtil.setPropertyDefault(newRow, "updateDate", null);
        return newRow;
    }


    public static MultiRow getPageEventSrcRow(SimpleCoreForm form, int tabIdx, String pageEventSrc) {
    	if (!CommonUtil.isValidInteger(pageEventSrc)) {
    		return null;
    	}
    	int idx = Integer.parseInt(pageEventSrc);
    	ArrayList rows = form.getMultiRows(tabIdx);
    	if (idx >= rows.size()) {
    		return null;
    	}
    	return (MultiRow)rows.get(idx);
    }

    public static String openSearchCategoryTreeDo() {
        return openPopWindow("popupCatalogTree.do", "popupCatalogTreeWin", "600", "450", "yes", "no", "yes", "yes", true);
    }

    public static String getCustName(HttpSession session, String custCode){
    	String companyCode = getAppropriateCompanyCode(session);
    	String query  = "SELECT CUST_NAME FROM T_CUST_HDR WHERE " +
        "COMPANY_CODE = '" + companyCode + "' AND " +
        "CUST_CODE = '" + custCode+ "' ";
    	return CommonUtil.nullStrToString(String.valueOf((new SelectDelegate()).selectOneValue(query)));
    }

    public static String getCustBrandName(HttpSession session, String custCode, String lineNo){    	
    	String query  = " "
        	;
    	return CommonUtil.nullStrToString(String.valueOf((new SelectDelegate()).selectOneValue(query)));
    }
    
    public static String getCustTeamName(HttpSession session, String custCode, String lineNo){    	
    	String query  = " SELECT CUST_TEAM FROM T_CUST_TEAM WHERE "
        	+ " COMPANY_CODE = '"+getAppropriateCompanyCode(session)+"' "
        	+ " AND CUST_CODE = '"+custCode+"' "        	
        	+ " AND LINE_NO = " + lineNo
        	;
    	return CommonUtil.nullStrToString(String.valueOf((new SelectDelegate()).selectOneValue(query)));
    }
    
    public static String getDeptName(HttpSession session, String deptCode){
    	String companyCode = getAppropriateCompanyCode(session);
    	String query  = "SELECT DEPT_NAME FROM T_DEPT_HDR WHERE " +
        "COMPANY_CODE = '" + companyCode + "' AND " +
        "DEPT_CODE = '" + deptCode+ "' ";
    	return CommonUtil.nullStrToString(String.valueOf((new SelectDelegate()).selectOneValue(query)));
    }

    public static String getModuleDesc(HttpSession session, String moduleCode){
    	String companyCode = getAppropriateCompanyCode(session);
    	String query  = "SELECT REF_DESC  FROM T_CODE_DTL WHERE " +
        "COMPANY_CODE = '" + companyCode + "' AND " +
        "REF_CODE = '" + moduleCode+ "' ";
    	return CommonUtil.nullStrToString(String.valueOf((new SelectDelegate()).selectOneValue(query)));
    }
    public static String getProjFabricGroup(HttpSession session, String projNo){
    	String companyCode = getAppropriateCompanyCode(session);
    	String query = " SELECT FABRIC_GROUP FROM T_PROJ_HDR WHERE " 
    				 + " COMPANY_CODE = '" + companyCode + "' "
    				 + " AND PROJ_NO = '" + projNo+ "' ";
    	return CommonUtil.nullStrToString(String.valueOf((new SelectDelegate()).selectOneValue(query)));
    }
    
    public static String getMillItemCode(HttpSession session, String fabricCode) {
    	String companyCode = getAppropriateCompanyCode(session);
    	String query = " SELECT VENDOR_ITEM_CODE FROM T_FABRIC_HDR WHERE " 
    				 + " COMPANY_CODE = '" + companyCode + "' "
    				 + " AND FABRIC_CODE = '" + fabricCode+ "' ";
    	return CommonUtil.nullStrToString(String.valueOf((new SelectDelegate()).selectOneValue(query)));
    }
    public static boolean validateProjNo(String code, String msg, ActionErrors errors) {
        boolean validCode = WebUtil.isProjNo(code);
        if (!validCode) {
            ActionErrorUtil.addErrorForSpecficPurpose(errors, msg);
        }
        return validCode;
    }
      
    public static boolean isProjNo(String code) {
        if (isEmpty(code)) return false;
        char[] codeArray = code.toCharArray();
        for(int i = 0; i < codeArray.length; ++i) {
        	if((codeArray[i] >= 'a' && codeArray[i] <= 'z')
        			|| (codeArray[i] >= 'A' && codeArray[i] <= 'Z')
        			|| (codeArray[i] == '-')
        			|| (codeArray[i] == '_')
        			|| (codeArray[i] >= '0' && codeArray[i] <= '9')) {
        		continue;
        	} else return false;
        }
        return true;
    }
    
    public static String openOsTaskSummary() {
        return openPopWindow("osTask.do", "osTaskSummary", "800", "600", "yes", "no", "yes", "yes", true);

    }
    
    public static String getProjStyleTaskStyleDesc(HttpSession session,
    		String projNo, String lineNo, String styleNo){
    	String companyCode = getAppropriateCompanyCode(session);
    	String query  = "SELECT DECODE(description,NULL, description, '-'||description) FROM T_PROJ_STYLE WHERE " +
        "COMPANY_CODE = '" + companyCode + "' AND " +
        "PROJ_NO = '" + projNo+ "' AND " +
        "LINE_NO = " + lineNo + 
        " AND STYLE_NO='" + styleNo + "'";
    	return CommonUtil.nullStrToString(String.valueOf((new SelectDelegate()).selectOneValue(query)));
    }
    
    public static String openPopupStyleTaskDtlDetailDo() {    
        return openPopWindow("popupStyleTaskDtlDetail.do?pageEvent=doNothing", "popupStyleTaskDtlDetail", "900", "400", "yes", "no", "yes", "yes", true);
    }

    public static String openPopupFabricTaskDtlDetailDo() {    
        return openPopWindow("popupFabricTaskDtlDetail.do?pageEvent=doNothing", "popupFabricTaskDtlDetail", "900", "400", "yes", "no", "yes", "yes", true);
    }
    
}